<template>
  <div class="main member-list">
    <div class="filter-container">
      <el-select v-model="listQuery.searchType" clearable placeholder="请选择查询类型" class="filter-item">
        <el-option :key="1" label="用户姓名" :value="1"></el-option>
        <el-option :key="2" label="用户手机号" :value="2"></el-option>
        <el-option :key="3" label="上级用户姓名" :value="3"></el-option>
        <el-option :key="4" label="上级用户手机号" :value="4"></el-option>
      </el-select>
      <el-input @keyup.enter.native="search" class="filter-item" placeholder="请输入" clearable
        v-model="listQuery.searchKey"></el-input>
      <el-select v-model="listQuery.level" clearable placeholder="请选择会员等级" class="filter-item">
        <el-option label="所有等级" value=""></el-option>
        <el-option v-for="(name, val) in levels" :key="val" :label="name" :value="val"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
    </div>
    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border highlight-current-row>
      <el-table-column align="center" label="昵称" prop="nickName">
        <template slot-scope="scope">
          <a v-if="rightsButtons['detail']" style="color: #409eff;" @click="relation_ship_click(scope.row.userId)">{{scope.row.nickName}}</a>
          <span v-else>{{scope.row.nickName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号" prop="mobileNo"></el-table-column>
      <el-table-column align="center" label="会员等级">
        <template slot-scope="scope">
          <router-link v-if="rightsButtons['levelOperateRecord']"
            :to="{name: 'boxTransUserLevelOperateRecord', params: { boxUserId : scope.row.userId}}"
            style="color: #409eff;">
            <span v-text="levels[scope.row.level]"></span>
          </router-link>
          <span v-else v-text="levels[scope.row.level]"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属上级姓名" prop="parentName"></el-table-column>
      <el-table-column align="center" label="上级号码" prop="parentMobileNo"></el-table-column>
      <el-table-column align="center" label="所属上级等级" prop="parentLevel">
        <template slot-scope="scope">
          <span v-text="levels[scope.row.parentLevel]"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="注册时间">
        <template slot-scope="scope">
          <div class="text-justify">
            <p v-text="formatDate(scope.row.registrationTime, 'YYYY-MM-DD HH:mm:ss')"></p>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="当前积分" prop="totalIntegral">
        <template slot-scope="scope">
          <router-link v-if="rightsButtons['integralOperateRecord']"
            :to="{name: 'boxTransUserIntegralOperateRecord', params: { boxUserId : scope.row.userId}}"
            style="color: #409eff;">
            {{scope.row.totalIntegral}}
          </router-link>
          <span v-else>{{scope.row.totalIntegral}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="280">
        <template slot-scope="scope">
          <el-button v-if="rightsButtons['edit']" type="primary" size="mini" @click="showModifyPop(scope.row)" plain>
            修改积分</el-button>
          <el-button v-if="rightsButtons['upgrade']" type="primary" size="mini" @click="enterUpgrade(scope.row)" plain>
            转入升级</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" v-if="total > 0">
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo"
        :page-size="listQuery.pageSize" :total="total" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>
    <el-dialog title="用户关系" :visible.sync="relation_ship_dialog" @close="close">
      <el-table :data="relation_ship_data" v-loading="relation_ship_loading" element-loading-text="给我一点时间" border
        highlight-current-row
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}">
        <el-table-column prop="nickName" label="用户昵称">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号码">
        </el-table-column>
        <el-table-column prop="level" label="用户等级">
          <template slot-scope="scope">
            {{levels[scope.row.level]}}
          </template>
        </el-table-column>
      </el-table>
      <p style="color: red;">*表格下一行为前一行的父级（推荐人）</p>
    </el-dialog>
    <el-dialog title="修改积分" :visible.sync="showEditPop" @close="cancelUpgradeSubmit">
      <el-form :model="upgrade" size="medium" ref="modifyUpgradeform" label-width="120px">
        <el-form-item prop="tradeType" :rules="commonRules.notNullRule">
          <el-radio-group v-model="upgrade.tradeType" @change="tradeTypeChange">
            <el-radio :label="301">充值转入</el-radio>
            <el-radio :label="401">财务扣除</el-radio>
            <el-radio :label="303">云仓转入</el-radio>
            <el-radio :label="402">云仓扣除</el-radio>
            <el-radio :label="201">提现核销</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="showTip" label-width="140px">
          <span>{{showIntegral}}</span><span style="color:#606266;margin-left:20px;"
            v-if="this.upgrade.tradeType==201">剩余可提现核销积分：{{showWithdrawableRemainTotal}}</span>
        </el-form-item>
        <el-form-item label="积分:" prop="transferIntegral" :rules="commonRules.priceRule">
          <el-input v-model="upgrade.transferIntegral"></el-input>
        </el-form-item>
        <el-form-item label="上传图片:">
          <el-upload class="avatar-uploader" accept="image/*" :action="upladUrl" name="file" :show-file-list="false"
            :on-success="uploadSuccess" :before-upload="beforeUpload">
            <img v-if="upgrade.picUrl" :src="upgrade.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注:" prop="remark" :rules="commonRules.notNullRule">
          <el-input type="textarea" maxlength="150" v-model="upgrade.remark" size="small"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="modifyIntegral" :disabled="btnDisabled">保存</el-button>
        <el-button @click="cancelUpgradeSubmit">取消</el-button>
      </div>
    </el-dialog>
    <!--详情-->
    <el-dialog title="用户详情" :visible.sync="showDetailPop">
      <el-form :model="detailInfo" size="medium" label-width="120px">
        <el-form-item label="昵称:" prop="nickName">
          {{detailInfo.nickName}}
        </el-form-item>
        <el-form-item label="手机号:" prop="mobileNo">
          {{detailInfo.mobileNo}}
        </el-form-item>
        <el-form-item label="会员等级:" prop="level">
          <span v-text="levels[detailInfo.level]"></span>
        </el-form-item>
        <el-form-item label="平台等级:" prop="oldUserRole">
          <span>
            <span v-if="detailInfo.oldUserRole==0||detailInfo.oldUserRole==1">普通会员</span>
            <span v-else-if="detailInfo.oldUserRole==2">大区</span>
            <span v-else-if="detailInfo.oldUserRole==3">董事</span>LV{{detailInfo.oldUserLevel}}
          </span>
        </el-form-item>
        <el-form-item label="所属上级:" prop="parentName">
          {{detailInfo.parentName}} {{detailInfo.parentMobileNo}}
        </el-form-item>
        <el-form-item label="所属上级等级:" prop="parentLevel">
          <span v-text="levels[detailInfo.parentLevel]"></span>
        </el-form-item>
        <el-form-item label="当前积分:" prop="totalIntegral">
          {{detailInfo.totalIntegral?detailInfo.totalIntegral:0}}
        </el-form-item>
        <el-form-item label="注册时间:" prop="registrationTime">
          <p v-text="formatDate(detailInfo.registrationTime, 'YYYY-MM-DD HH:mm:ss')"></p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDetailPop">确定</el-button>
      </div>
    </el-dialog>
    <!-- 转入升级 -->
    <el-dialog title="转入升级" :visible.sync="enterUpgradePop" @close="cancelUpgradeSubmit">
      <el-form :model="upgrade" :rules="commonRules" size="medium" ref="upgradeform" label-width="120px">
        <el-form-item label="可产生收益积分:" prop="integral">
          {{upgrade.integral}}
        </el-form-item>
        <el-form-item label="积分:" prop="transferIntegral" :rules="commonRules.priceRuleZero">
          <el-input v-model="upgrade.transferIntegral"></el-input>
        </el-form-item>
        <el-form-item label="上传图片:">
          <el-upload class="avatar-uploader" accept="image/*" :action="upladUrl" name="file" :show-file-list="false"
            :on-success="uploadSuccess" :before-upload="beforeUpload">
            <img v-if="upgrade.picUrl" :src="upgrade.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="赠送等级:" prop="level" :rules="commonRules.notNullRule">
          <el-select v-model="upgrade.level" clearable placeholder="请选择会员等级" class="filter-item">
            <el-option v-for="(name, val) in entryLevels" :key="val" :label="name" :value="val"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" prop="remark" :rules="commonRules.notNullRule">
          <el-input type="textarea" maxlength="150" v-model="upgrade.remark" size="small"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="upgradeSubmit">保存</el-button>
        <el-button @click="cancelUpgradeSubmit">取消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import {
    getUser
  } from '../../../utils/auth'
  export default {
    name: 'BoxTransUser',
    data() {
      return {
        relation_ship_data: [], //用户关系数据
        relation_ship_dialog: false, //用户关系dialog状态
        showTip: '可产生收益积分:',
        detailInfo: {},
        list: [],
        listQuery: {
          searchType: 1,
          searchKey: '',
          level: '',
          pageNo: 1,
          pageSize: 10
        },
        total: 0,
        levels: {}, //会员等级
        entryLevels: {}, //可赠送会员级别
        disabledBtn: false,
        showEditPop: false,
        showDetailPop: false,
        enterUpgradePop: false,
        userData: {},
        radio: 1,
        relation_ship_loading: false, //用户关系加载状态
        listLoading: false,
        btnDisabled: false,
        btnLoading: false,
        editItem: {},
        //转入升级对象
        upgrade: {
          nickName: '',
          boxUserId: '',
          level: '',
          picUrl: '',
          remark: '',
          tradeNo: '',
          tradeType: '',
          transferIntegral: 0
        },
        integral: 0,
        stockIntegral: 0,
        showIntegral: 0,
        withdrawableRemainTotal: 0,
        showWithdrawableRemainTotal: 0
      }
    },
    created() {
      this.userData = getUser()
      this.getLevelList();
      this.getList()
    },
    methods: {
      //获取等级列表
      async getLevelList(){
        await this.request({
          url: '/bsnl-product/box/privilege-commission-config/list',
          method: 'get',
          data: {
            pageIndex: 1,
            pageSize: 100,
            month: ''
          }
        }).then((res) => {
          this.entryLevels={};
          for (let s of res.data) {
            this.entryLevels[s.levelId]=s.levelName;//箱起可赠送会员不包括箱起会员
          }
          //箱起会员类型
          this.levels = JSON.parse(JSON.stringify(this.entryLevels))
          if(!this.levels['0']){
            this.levels['0']="箱起会员";
          }
        }).catch(err => {
          console.log(err)
        })
      },
      close() {
        //清空数据
        this.relation_ship_data = []
        this.relation_ship_loading = false
      },
      relation_ship_click(userId) {
        //打开dialog
        this.relation_ship_dialog = true
        this.relation_ship_loading = true
        this.relation_ship(userId)
        console.log(userId)
      },
      relation_ship(userId) {
        this.request({
          url: `/bsnl-product/box/user-level-info/level_relative?boxUserId=${userId}`,
          method: 'get',
          data: {
            pageSize: '',
            pageNo: ''
          }
        }).then(res => {
          if (res.status == 200) {
            this.relation_ship_data = res.data
            this.relation_ship_loading = false
          }
        })
      },
      tradeTypeChange(tradeType) {
        if (tradeType == '303' || tradeType == '402') {
          this.showTip = '不可产生收益积分:'
          this.showIntegral = this.stockIntegral
        } else if (tradeType == '201') {
          this.showTip = '可产生收益积分:'
          this.showIntegral = this.integral
          this.showWithdrawableRemainTotal = this.withdrawableRemainTotal
        } else {
          this.showTip = '可产生收益积分:'
          this.showIntegral = this.integral
        }
        this.upgrade.tradeType = tradeType
        this.fetchTradeNo(this.upgrade.tradeType)
      },
      uploadSuccess(res) {
        this.upgrade.picUrl = this.replaceImgUrl(res.filePath);
        //this.$refs.upgradeform.clearValidate(['picUrl']);
      },
      cancelUpgradeSubmit() {
        this.integral = 0
        this.withdrawableRemainTotal = 0
        this.stockIntegral = 0
        this.showIntegral = 0
        this.showWithdrawableRemainTotal = 0
        this.upgrade = {
          nickName: '',
          boxUserId: '',
          level: '',
          picUrl: '',
          remark: '',
          tradeNo: '',
          tradeType: '',
          transferIntegral: ''
        }
        this.enterUpgradePop = false
        this.showEditPop = false;
      },
      upgradeSubmit() {
        this.$refs.upgradeform.validate(valid => {
          if (valid) {
            this.$confirm('赠送' + this.upgrade.nickName + ' ' + this.upgrade.transferIntegral + '积分且等级升级为' + this
              .levels[this.upgrade.level], '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
              this.requireEntryApi()
            }).catch(err => {
              console.log(err)
            })
          }
        })
      },
      requireEntryApi() {
        this.request({
          url: '/bsnl-product/box/user-level-info/transfer-then-upgrade',
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          },
          data: this.upgrade
        }).then((res) => {
          if (res.status === 200) {
            this.$message.success('操作成功')
            this.cancelUpgradeSubmit()
            this.getList()
          }
        }).catch((err) => {
          this.$message.error(err.message)
        })
      },
      //转入升级
      enterUpgrade(row) {
        this.upgrade.nickName = row.nickName
        this.upgrade.tradeType = 302
        this.upgrade.integral = row.integral
        this.upgrade.boxUserId = row.userId
        this.enterUpgradePop = true
        this.fetchTradeNo(this.upgrade.tradeType)
        this.$refs.upgradeform.clearValidate([]);
      },
      fetchTradeNo(tradeType) {
        //获取交易单号
        this.request({
          url: '/bsnl-product/box/common/trade-no',
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          },
          data: {
            tradeType: tradeType
          }
        }).then((res) => {
          if (res.status === 200) {
            this.upgrade.tradeNo = res.data
          }
        }).catch((err) => {
          this.btnLoading = false
          this.$message.error('获取交易号失败,请重新尝试获取')
        })
      },
      closeDetailPop() {
        this.showDetailPop = false
      },
      viewInfo(row) {
        this.detailInfo = row
        this.showDetailPop = true
      },
      showModifyPop(row) {
        this.integral = row.integral
        this.withdrawableRemainTotal = row.withdrawableRemainTotal;
        this.stockIntegral = row.stockIntegral

        this.upgrade.boxUserId = row.userId
        this.showEditPop = true;
        this.btnDisabled = false;
        this.$refs.modifyUpgradeform.clearValidate([]);
      },
      modifyIntegral() {
        this.$refs.modifyUpgradeform.validate(valid => {
          if (valid) {
            this.requireEntryApi()
          }
        })
      },
      // 获取列表
      getList() {
        this.listLoading = true
        this.request({
            url: '/bsnl-product/box/user-level-info/list',
            method: 'get',
            params: this.listQuery
          })
          .then(res => {
            this.list = res.data
            this.total = res.totalCount
            this.listLoading = false
          })
          .catch(err => {
            console.log(err)
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      // 搜索
      search() {
        this.listQuery.pageNo = 1
        this.getList()
      },
      // 切换分页
      handleCurrentChange(page) {
        this.listQuery.pageNo = page
        this.getList()
      }
    }
  }
</script>
